package com.itheima.wallet.user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.wallet.user.api.UserRegisterServiceApi;
import com.itheima.wallet.user.mapper.AccountMapper;
import com.itheima.wallet.user.mapper.UserMapper;

import com.itheima.wallet.user.pojos.Account;
import com.itheima.wallet.user.pojos.User;
import com.itheima.wallet.user.vo.ErrorResult;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

@Service(version = "1.0.0")
public class UserRegisterService implements UserRegisterServiceApi {
    //注入mapper层
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AccountMapper accountMapper;

    //注入redis
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    /**
     *  保存用户信息的方法
     * @param param 请求参数（包含了用户的信息）
     * @return 结果状态封装类
     */
    @Override
    public ErrorResult saveUserInfo(Map<String, String> param) {
        try {
            //判断参数
            if(param.size()==0){
                //如果参数为空则返回错误提示信息
                String mes = "参数有误";
                ErrorResult errorResult = new ErrorResult();
                errorResult.setErrCode("000003");
                errorResult.setErrMessage(mes);
                return errorResult;
            }
            String phone = param.get("phone");
            //如果参数没有问题，查询redis中的验证码
            String redisKey = "CHECK_CODE_"+phone;
            String redisValue = this.redisTemplate.opsForValue().get(redisKey);
            //判断查询的值
            if(null==redisValue|| !(StringUtils.equals(redisValue,param.get("code")))){
                //如果没有查询到验证码
                String mes = "验证码无效";
                ErrorResult errorResult = new ErrorResult();
                errorResult.setErrCode("000007");
                errorResult.setErrMessage(mes);
                return errorResult;
            }

            //如果不为空,查询数据库有没有该用户的信息

            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone",phone);
            User result = this.userMapper.selectOne(queryWrapper);
            if(null != result){
                //如果user不为空则 ,则说明是已注册用户
                String mes = "该账号已经注册过了";
                ErrorResult errorResult = new ErrorResult();
                errorResult.setErrCode("000006");
                errorResult.setErrMessage(mes);
                return errorResult;
            }
            //如果为空则表示为新用户，把数据存到数据库中
            User user = new User();
            user.setUsername(param.get("username"));
            user.setPassword(DigestUtils.md5Hex(param.get("password")));
            //long time = new Date().getTime();

            user.setCreateTime(new Date());
            user.setPhone(phone);

            user.setAccountId(RandomUtils.nextLong(100000,9999999));
            int count = this.userMapper.insert(user);
            if(count<1){
               //如果count小于1则保存失败
                String mes = "保存失败";
                ErrorResult errorResult = new ErrorResult();
                errorResult.setErrCode("000002");
                errorResult.setErrMessage(mes);

                return errorResult;
            }
            //反之则保存成功,开通用户的钱包功能
            Account account = new Account();
            account.setAccountId(user.getAccountId());
            account.setAccountName(user.getUsername());
            account.setCreateTime(new Date());
            account.setBalance(0.0);
            int insert = this.accountMapper.insert(account);
            if (insert<1){
                //如果count小于1则保存失败
                String mes = "保存失败";
                ErrorResult errorResult = new ErrorResult();
                errorResult.setErrCode("000002");
                errorResult.setErrMessage(mes);

                return errorResult;
            }


            return  null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        //如果出错
        String mes = "服务器内部错误";
        ErrorResult errorResult = new ErrorResult();
        errorResult.setErrCode("000004");
        errorResult.setErrMessage(mes);
        return errorResult;
    }
}
